<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>编辑公告</span>
		</div>
		<el-form :model="form" ref="form" :rules="rules" label-width="100px">
			<el-form-item label="标题" prop="title">
				<el-input v-model="form.title"></el-input>
			</el-form-item>
			<el-form-item label="置顶" prop="is_sticky ">
				<el-radio-group v-model="form.is_sticky">
					<el-radio label="1">是</el-radio>
					<el-radio label="0">否</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="内容" prop="content">
				<div style="border: 1px solid #ccc;">
					<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
						:mode="mode" />
					<Editor style="height: 500px; overflow-y: hidden;" v-model="form.content"
						:defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
				</div>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleEdit">发布公告</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
	import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
	import '@wangeditor/editor/dist/css/style.css';
	import { Notice } from "@/api";
	export default {
		name: 'Edit',
		// 布局注册
		components: { Editor, Toolbar },
		data() {
			return {
				form: {
					title: '',
					is_sticky: '',
					// 富文本编辑器的内容在html内
					content: '',
				},
				editor: null,
				toolbarConfig: {},
				editorConfig: { placeholder: '请输入内容...' },
				mode: 'default', // or 'simple' 简化版
				rules: {
					title: [{ required: true, message: "请填写公告标题！", trigger: 'blur' }],
					is_sticky: [{ required: true, message: "请选择置顶情况！", trigger: 'blur' }],
					content: [{ required: true, message: "请输入公告内容！", trigger: 'blur' }, ],
				},
			}
		},
		created() {
			// 获取地址栏参数
			let { notice_id } = this.$route.params;
			this.init(notice_id);
			document.title = "编辑公告";
		},
		methods: {
			async init(notice_id) {
				let { status, data } = await Notice.detail({ notice_id });
				if (status) {
					// 还原表单：data返回的数据中包含notice_id
					data.is_sticky = data.is_sticky.toString(); // 将 is_sticky 转换为字符串类型
					this.form = data;
				}
			},
			onCreated(editor) {
				this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
			},
			// 编辑公告
			handleEdit() {
				this.$refs.form.validate(async (valid) => {
					if (valid) {
						let { status, msg } = await Notice.edit({ ...this.form });
						if (status) {
							this.$message.success(msg);
							this.$router.push('/notice/list');
						} else {
							this.$message.error(msg);
						}
					}
				});
			}
		},
		beforeDestroy() {
			const editor = this.editor
			if (editor == null) return
			editor.destroy() // 组件销毁时，及时销毁编辑器
		}
	}
</script>

<style>
	.el-input {
		margin-right: 30px;
	}
</style>
